<script setup>
import { ref, onMounted, computed } from 'vue';
import { useUserStore } from '@/stores/user';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '@/utils/http';

const userStore = useUserStore();

// 用户信息
const userInfo = ref(null);
// 编辑模式
const isEditMode = ref(false);
// 加载状态
const loading = ref(false);
// 错误信息
const error = ref(null);

// 表单数据
const formData = ref({
  userName: '',
  userAvatar: '',
  userProfile: ''
});

// 计算属性：用户角色显示名称
const userRoleDisplay = computed(() => {
  if (!userInfo.value) return '';
  
  switch (userInfo.value.userRole) {
    case 'admin':
      return '管理员';
    case 'user':
      return '普通用户';
    default:
      return userInfo.value.userRole;
  }
});

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true;
  error.value = null;
  
  try {
    // 使用用户存储中的当前用户信息
    if (userStore.currentUser) {
      userInfo.value = userStore.currentUser;
      // 初始化表单数据
      formData.value.userName = userInfo.value.userName || '';
      formData.value.userAvatar = userInfo.value.userAvatar || '';
      formData.value.userProfile = userInfo.value.userProfile || '';
    } else {
      // 如果用户存储中没有用户信息，尝试重新获取
      await userStore.initUser();
      userInfo.value = userStore.currentUser;
      if (userInfo.value) {
        formData.value.userName = userInfo.value.userName || '';
        formData.value.userAvatar = userInfo.value.userAvatar || '';
        formData.value.userProfile = userInfo.value.userProfile || '';
      }
    }
  } catch (err) {
    console.error('获取用户信息失败:', err);
    error.value = '获取用户信息失败，请稍后再试';
  } finally {
    loading.value = false;
  }
};

// 切换编辑模式
const toggleEditMode = () => {
  if (isEditMode.value) {
    // 退出编辑模式，重置表单数据
    formData.value.userName = userInfo.value.userName || '';
    formData.value.userAvatar = userInfo.value.userAvatar || '';
    formData.value.userProfile = userInfo.value.userProfile || '';
  }
  isEditMode.value = !isEditMode.value;
};

// 更新用户信息
const updateUserInfo = async () => {
  // 表单验证
  if (!formData.value.userName) {
    ElMessage.warning('用户名不能为空');
    return;
  }
  
  loading.value = true;
  try {
    // 调用更新接口
    await http.post('/user/update/my', {
      userName: formData.value.userName,
      userAvatar: formData.value.userAvatar,
      userProfile: formData.value.userProfile
    });
    
    // 更新成功后，重新获取用户信息
    await userStore.initUser();
    userInfo.value = userStore.currentUser;
    
    // 退出编辑模式
    isEditMode.value = false;
    
    ElMessage.success('个人信息更新成功');
  } catch (err) {
    console.error('更新用户信息失败:', err);
    ElMessage.error(err.response?.data?.message || '更新失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo();
});
</script>

<template>
  <div class="user-profile-container">
    <div class="profile-header">
      <h1 class="page-title">个人中心</h1>
    </div>
    
    <div v-if="loading" class="loading-state">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <div v-else-if="error" class="error-state">
      <p>{{ error }}</p>
      <button @click="fetchUserInfo" class="btn-primary">重试</button>
    </div>
    
    <div v-else-if="!userInfo" class="not-found-state">
      <p>未找到用户信息，请先登录</p>
      <router-link to="/login" class="btn-primary">去登录</router-link>
    </div>
    
    <div v-else class="profile-content">
      <!-- 查看模式 -->
      <div v-if="!isEditMode" class="view-mode">
        <div class="profile-card">
          <div class="avatar-section">
            <img 
              :src="userInfo.userAvatar || require('@/assets/default-avatar.png')" 
              alt="用户头像" 
              class="user-avatar"
            />
          </div>
          
          <div class="info-section">
            <div class="info-item">
              <span class="info-label">用户名</span>
              <span class="info-value">{{ userInfo.userName || '未设置' }}</span>
            </div>
            
            <div class="info-item">
              <span class="info-label">用户角色</span>
              <span class="info-value">{{ userRoleDisplay }}</span>
            </div>
            
            <div class="info-item">
              <span class="info-label">个人简介</span>
              <span class="info-value profile-text">{{ userInfo.userProfile || '未设置个人简介' }}</span>
            </div>
          </div>
          
          <div class="action-section">
            <button @click="toggleEditMode" class="btn-primary edit-btn">
              编辑资料
            </button>
          </div>
        </div>
      </div>
      
      <!-- 编辑模式 -->
      <div v-else class="edit-mode">
        <div class="profile-card">
          <div class="avatar-section">
            <img 
              :src="formData.userAvatar || require('@/assets/default-avatar.png')" 
              alt="用户头像" 
              class="user-avatar"
            />
            <div class="avatar-input">
              <label for="avatar-url" class="form-label">头像URL</label>
              <input 
                type="text" 
                id="avatar-url" 
                v-model="formData.userAvatar" 
                placeholder="请输入头像图片URL"
                class="form-input"
              />
            </div>
          </div>
          
          <div class="form-section">
            <div class="form-group">
              <label for="username" class="form-label">用户名</label>
              <input 
                type="text" 
                id="username" 
                v-model="formData.userName" 
                placeholder="请输入用户名"
                class="form-input"
              />
            </div>
            
            <div class="form-group">
              <label for="user-profile" class="form-label">个人简介</label>
              <textarea 
                id="user-profile" 
                v-model="formData.userProfile" 
                placeholder="请输入个人简介"
                class="form-textarea"
                rows="4"
              ></textarea>
            </div>
          </div>
          
          <div class="action-section">
            <button @click="toggleEditMode" class="btn-secondary cancel-btn">
              取消
            </button>
            <button @click="updateUserInfo" class="btn-primary save-btn" :disabled="loading">
              {{ loading ? '保存中...' : '保存' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.user-profile-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem;
}

.profile-header {
  margin-bottom: 2rem;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 1rem;
}

.page-title {
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--text-color);
  margin: 0;
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.profile-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 2rem;
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1.5rem;
}

.user-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid var(--primary-color);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.avatar-input {
  width: 100%;
  max-width: 400px;
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.info-label {
  font-size: 0.875rem;
  color: var(--light-text-color);
  font-weight: 500;
}

.info-value {
  font-size: 1rem;
  color: var(--text-color);
  font-weight: 500;
}

.profile-text {
  white-space: pre-line;
  line-height: 1.6;
}

.action-section {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1rem;
}

.form-section {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.form-label {
  font-size: 0.875rem;
  color: var(--light-text-color);
  font-weight: 500;
}

.form-input,
.form-textarea {
  padding: 0.75rem 1rem;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
  width: 100%;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.1);
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
}

.btn-primary,
.btn-secondary {
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 500;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
}

.btn-primary {
  background-color: var(--primary-color);
  color: white;
}

.btn-primary:hover {
  background-color: var(--primary-hover-color);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}

.btn-primary:disabled {
  background-color: #a5a5a5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-secondary {
  background-color: transparent;
  color: var(--text-color);
  border: 1px solid var(--border-color);
}

.btn-secondary:hover {
  background-color: #f3f4f6;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 加载、错误和未找到状态 */
.loading-state,
.error-state,
.not-found-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 3rem;
  text-align: center;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(79, 70, 229, 0.1);
  border-radius: 50%;
  border-top-color: var(--primary-color);
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (min-width: 768px) {
  .profile-card {
    flex-direction: row;
    align-items: flex-start;
  }
  
  .avatar-section {
    width: 30%;
  }
  
  .info-section,
  .form-section {
    width: 70%;
  }
}
</style>